package com.arong.swing.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;

import com.arong.swing.config.Config;

public class Tools {
	// java启动参数的目录
	private static String APP_HOME = null;

	// 初始化常量
	static {
		APP_HOME = System.getProperty("APP_HOME");
		if (APP_HOME == null) {
			APP_HOME = "./";
		}
	}

	public static String getAppHome() {
		return APP_HOME;
	}
	public static void checkUsableSpace(File diskPartition) throws Exception {
    	 long usablePatitionSpace = diskPartition.getUsableSpace(); 
    	 long usableGB = usablePatitionSpace / (1024 *1024*1024);
    	 if(usableGB < 2){
    		 throw new Exception("磁盘空间不足，布控包需要至少2G磁盘空间!");
    	 }
	}
	public static boolean switchDirName(File tmpFile, File dbFile) throws InterruptedException {
		boolean reNameOk = false;
		
		if(!dbFile.exists()){
			return true;
		}
		
		int count = 0;
		while(!reNameOk){
			try{
				if(!dbFile.exists()){
					break;
				}
				
				reNameOk =dbFile.renameTo(tmpFile);
				count++;
				if(count >6){
					break;
				}
			}catch(Exception e){
				e.printStackTrace();
				Thread.sleep(300);
			}
		}
		if(!reNameOk){
			throw new InterruptedException("rename errors.");
		}
		return reNameOk;
	}
	public static InputStream getFileInput(String filePath) throws FileNotFoundException {
		InputStream inputFile = null;
		if (filePath.startsWith("/")) {
			inputFile = new FileInputStream(filePath);
		} else {
			inputFile = new FileInputStream(Tools.getAppHome() + filePath);
		}
		return inputFile;
	}
	public static File getFile(String filePath) throws IOException {
		File file = null;
		if (filePath.startsWith("/")) {
			file = new File(filePath);
		} else {
			file = new File(Tools.getAppHome() + filePath);
		}
		if(!file.exists()){
			file.createNewFile();
		}
		return file;
	}
	
	/**
	 * 返回本机能够访问远程服务的本机的对应ip地址
	 * @param remoteIp
	 * @param port
	 * @return
	 */
	public static boolean reachableIP(){ 
		String remoteIp = Config.get().getString("httpService.ip","127.0.0.1");
		int port = 80;
		String portStr = Config.get().getValue("httpService.port");
		if (portStr != null && portStr.trim().length() > 0) {
			port = Integer.valueOf(portStr);
		}
		
		Enumeration<NetworkInterface> netInterfaces;
		try {
			InetAddress remoteAddr = InetAddress.getByName(remoteIp);
			netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> localAddrs = ni.getInetAddresses();
				while (localAddrs.hasMoreElements()) {
					InetAddress localAddr = localAddrs.nextElement();
					if (isReachable(localAddr, remoteAddr, port, 5000)) {
						String retIP = localAddr.getHostAddress();
						return true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;   
	 }  
	 
	public static String getObjectNotNullValue(String value){
		return value ==null?"":value;
	}
	private static boolean isReachable(InetAddress localInetAddr, InetAddress remoteInetAddr, 
	                   int port, int timeout) { 
		boolean isReachable = false;
		Socket socket = null;
		try {
			socket = new Socket();
			// 端口号设置为 0 表示在本地挑选一个可用端口进行连接
			SocketAddress localSocketAddr = new InetSocketAddress(
					localInetAddr, 0);
			socket.bind(localSocketAddr);
			InetSocketAddress endpointSocketAddr = new InetSocketAddress(
					remoteInetAddr, port);
			socket.connect(endpointSocketAddr, timeout);
			isReachable = true;
		} catch (IOException e) {
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
				}
			}
		}
	    return isReachable; 
	 }
	
	
	public static String findURootPath(){
	    //FileSystemView sys = FileSystemView.getFileSystemView();
	    //循环盘符
	    File[] files = File.listRoots(); 
	    /*for(File file:files){
	      //得到系统中存在的C:\,D:\,E:\,F:\,H:\
	      System.out.println("系统中存在的"+file.getPath());
	    }*/
	   /* File file = null;
	    String path = null;
	    for(int i = 0; i < files.length; i++) { 
	      //得到文字命名形式的盘符系统 (C:)、软件 (D:)、公司文档 (E:)、测试U盘 (H:)
	      System.out.println("得到文字命名形式的盘符"+sys.getSystemDisplayName(files[i]));
	      if(sys.getSystemDisplayName(files[i]).contains("测试U盘")){
	        file = files[i];
	        break;
	      }
	    }*/
	   /* if(file!=null){
	      path = file.getPath();
	    }*/
	    return files[files.length-1].getPath();
	  }
	/**
	 * 根据用户生日计算年龄
	 */
	public static int getAgeByBirthday(Date birthday) {
		Calendar cal = Calendar.getInstance();

		if (cal.before(birthday)) {
			throw new IllegalArgumentException(
					"The birthDay is before Now.It's unbelievable!");
		}

		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

		cal.setTime(birthday);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

		int age = yearNow - yearBirth;

		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				// monthNow==monthBirth 
				if (dayOfMonthNow < dayOfMonthBirth) {
					age--;
				}
			} else {
				// monthNow>monthBirth 
				age--;
			}
		}
		return age;
	}
	public static void main(String[] args) throws InterruptedException {
		
		
		//System.out.println(findURootPath());
		Tools.switchDirName(new File("E:\\temp\\SwingCK_new"),new File("E:\\temp\\SwingCK_new-1"));
	}
}
